package com.example.cardgame;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AlertDialog;
public class CardGameActivity extends AppCompatActivity {

    private GridLayout gridLayout;
    private TextView tvScore, tvProgress;
    private Button btnReset, btnExit;
    private CardGameModel gameModel;
    private int highScore;

    private static final int CARD_BACK = R.drawable.card_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_card_game);

        highScore = getIntent().getIntExtra("highScore", 0);
        initViews();
        initGame();
    }

    private void initViews() {
        gridLayout = findViewById(R.id.grid_layout);
        tvScore = findViewById(R.id.tv_score);
        tvProgress = findViewById(R.id.tv_progress);
        btnReset = findViewById(R.id.btn_reset);
        btnExit = findViewById(R.id.btn_exit);

        setupClickListeners();
    }

    private void initGame() {
        gameModel = new CardGameModel();
        createCardGrid();
        updateUI();
    }

    private void createCardGrid() {
        gridLayout.removeAllViews();

        int screenWidth = getResources().getDisplayMetrics().widthPixels;
        int cardSize = (screenWidth - 60) / 4; // 减去padding

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                ImageButton card = new ImageButton(this);

                GridLayout.LayoutParams params = new GridLayout.LayoutParams();
                params.width = cardSize;
                params.height = cardSize;
                params.setMargins(5, 5, 5, 5);
                params.rowSpec = GridLayout.spec(i);
                params.columnSpec = GridLayout.spec(j);

                card.setLayoutParams(params);
                card.setBackgroundResource(R.drawable.card_background);
                card.setScaleType(ImageView.ScaleType.CENTER_CROP);
                card.setImageResource(CARD_BACK);
                card.setTag(new int[]{i, j});

                card.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        handleCardClick(v);
                    }
                });

                gridLayout.addView(card);
            }
        }
    }

    private void handleCardClick(View v) {
        int[] position = (int[]) v.getTag();
        int row = position[0];
        int col = position[1];

        if (gameModel.isFlipped(row, col)) {
            return; // 已经翻开的卡片不能再点击
        }

        // 翻开卡片
        gameModel.flipCard(row, col);
        ImageButton card = (ImageButton) v;
        card.setImageResource(gameModel.getCard(row, col));

        if (gameModel.getFirstFlippedRow() != -1 && gameModel.getFirstFlippedCol() != -1) {
            // 已经翻开两张卡片，检查匹配
            final int firstRow = gameModel.getFirstFlippedRow();
            final int firstCol = gameModel.getFirstFlippedCol();

            if (gameModel.getScore() > 0 && firstRow != row && firstCol != col) {
                // 延迟检查匹配结果
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        checkCardMatch(firstRow, firstCol, row, col);
                    }
                }, 1000);
            }
        }

        updateUI();

        // 检查游戏是否完成
        if (gameModel.isGameCompleted()) {
            showGameCompleteDialog();
        }
    }

    private void checkCardMatch(int firstRow, int firstCol, int secondRow, int secondCol) {
        ImageButton firstCard = getCardAtPosition(firstRow, firstCol);
        ImageButton secondCard = getCardAtPosition(secondRow, secondCol);

        if (gameModel.getCard(firstRow, firstCol) != gameModel.getCard(secondRow, secondCol)) {
            // 不匹配，翻回去
            firstCard.setImageResource(CARD_BACK);
            secondCard.setImageResource(CARD_BACK);
            gameModel.unflipCard(firstRow, firstCol);
            gameModel.unflipCard(secondRow, secondCol);
        }

        gameModel.resetFlippedCount();
        updateUI();
    }

    private ImageButton getCardAtPosition(int row, int col) {
        for (int i = 0; i < gridLayout.getChildCount(); i++) {
            View child = gridLayout.getChildAt(i);
            int[] position = (int[]) child.getTag();
            if (position[0] == row && position[1] == col) {
                return (ImageButton) child;
            }
        }
        return null;
    }

    private void updateUI() {
        tvScore.setText(getString(R.string.score_label) + gameModel.getScore());
        tvProgress.setText("3 / 3"); // 可以改为显示剩余机会等
    }

    private void setupClickListeners() {
        btnReset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                resetGame();
            }
        });

        btnExit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitGame();
            }
        });
    }

    private void resetGame() {
        gameModel.resetGame();
        createCardGrid();
        updateUI();
    }

    private void exitGame() {
        Intent resultIntent = new Intent();
        resultIntent.putExtra("newScore", gameModel.getScore());
        setResult(RESULT_OK, resultIntent);
        finish();
    }

    private void showGameCompleteDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("游戏完成")
                .setMessage("恭喜！你的得分是: " + gameModel.getScore())
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        exitGame();
                    }
                })
                .setCancelable(false)
                .show();
    }
}